package zengjin.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zengjin.common.R;
import zengjin.model.vo.UserVO;
import zengjin.service.UserService;

/**
 * @author 19324
 */
@Tag(name = "用户相关接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;


    //1. 用户登录
    @Operation(summary = "用户登录")
    @PostMapping ("/login")
    public R<UserVO> login(String account, String password, HttpServletRequest request) {
        //1.参数校验
        if (account == null || password == null || request == null) {
            return R.error(null, "参数为空");
        }
        //2.调用service
        UserVO userVO = userService.login(account, password, request);
        if (userVO == null) {
            return R.error(null, "账号不存在或者账号密码错误");
        }
        return R.success(userVO, "登录成功");
    }

    //2. 用户注册
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public R<Boolean> register(String account, String password,String role) {
        //1.参数校验
        if (account == null || password == null || role == null) {
            throw new RuntimeException("参数为空");
        }
        //2.调用service
        Boolean registerResult =userService.register(account, password,role);
        if (!registerResult) {
            return R.error(false, "注册失败");
        }
        return R.success(true, "注册成功");
    }

    //3. 用户注销
    @Operation(summary = "用户注销")
    @PostMapping("/logout")
    public R<Boolean> logout(HttpServletRequest request,String account) {
        //1.参数校验
        if (request == null|| account == null) {
            throw new RuntimeException("参数为空");
        }
        //2.调用service
        Boolean logoutResult = userService.logout(request, account);
        if (!logoutResult) {
            return R.error(false, "退出失败");
        }
        return R.success(true, "退出成功");
    }

    //4.重置密码
    @Operation(summary = "重置密码")
    @PostMapping("/resetPassword")
    public R<Boolean> resetPassword(String account, String password,String role) {
        //1.参数校验
        if (account == null || password == null || role == null) {
            throw new RuntimeException("参数为空");
        }
        //2.调用service
        boolean resetPasswordResult = userService.resetPassword(account, password, role);
        if (!resetPasswordResult) {
            return R.error(false, "重置密码失败");
        }
        return R.success(true, "重置密码成功，请重新登录");
    }


}
